﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Otgruzka.Controls
{
    public partial class ScrolledCheckBoxList : System.Web.UI.UserControl
    {
        public string TitleText { get; set; }
        public string DataTextField { get; set; }
        public string DataValueField { get; set; }
        public object DataSource { get; set; }
        public List<int> SelectedValues 
        {
            get 
            {
                List<int> selectedList = null;
                if (checkBoxList.Items != null && checkBoxList.Items.Count > 0)
                {
                    selectedList = new List<int>();
                    foreach (ListItem item in checkBoxList.Items)
                        if (item.Selected)
                            selectedList.Add(Convert.ToInt32(item.Value));
                }
                return selectedList;
            }
            set 
            {
                if (checkBoxList.DataSource != null && checkBoxList.Items.Count > 0)
                {
                    foreach (ListItem item in checkBoxList.Items)
                    {
                        if (value == null || value.Count == 0 || !value.Contains(Convert.ToInt32(item.Value)))
                            item.Selected = false;
                        else
                            item.Selected = true;
                    }
                }
            }
        }

        public string Width { get; set; }
        public string Height { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        void Page_PreRender(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.Width))
                this.Width = "120px";
            if (string.IsNullOrEmpty(this.Height))
                this.Height = "100px";
        }


        public void DataBind()
        {
            if (this.DataSource != null)
            {
                checkBoxList.DataTextField = this.DataTextField;
                checkBoxList.DataValueField = this.DataValueField;

                checkBoxList.DataSource = this.DataSource;
                checkBoxList.DataBind();

                foreach (ListItem item in checkBoxList.Items)
                {
                    item.Attributes["onClick"] = "changeColor(this);";
                }
            }
        }

        public void SelectAll()
        {
            if (checkBoxList.Items != null)
                foreach (ListItem item in checkBoxList.Items)
                    item.Selected = true;
        }

        public void ClearSelection()
        {
            if (checkBoxList.Items != null)
                foreach (ListItem item in checkBoxList.Items)
                    item.Selected = false;
        }


    }
}